package com.fly.show.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fly.show.entity.JsonResult;
import com.fly.show.service.GitService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "git接口")
@RestController
@RequestMapping("/git")
public class GitController
{
    @Autowired
    GitService gitService;
    
    AtomicInteger count = new AtomicInteger(0);
    
    Resource resource = new ClassPathResource("data/error.zip");
    
    @ApiOperation("项目遍历")
    @ApiOperationSupport(order = 10)
    @GetMapping("/list")
    public List<String> list()
    {
        return gitService.getSubNames();
    }
    
    @ApiOperation("项目查询")
    @ApiOperationSupport(order = 20)
    @ApiImplicitParam(name = "name", value = "项目名称", required = true)
    @GetMapping("/query")
    public JsonResult<?> query(String name)
    {
        List<String> names = gitService.getSubNames(name);
        if (names.isEmpty())
        {
            return JsonResult.error("未发现任何项目");
        }
        return JsonResult.success(names);
    }
    
    @ApiOperation("项目下载")
    @ApiOperationSupport(order = 30)
    @ApiImplicitParam(name = "name", value = "项目名称", required = true)
    @GetMapping(value = "/down", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void down(String name, HttpServletResponse response)
        throws IOException
    {
        try
        {
            // 使用计数器控制并发
            if (count.incrementAndGet() > 5)
            {
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
                response.getWriter().print("请求用户过多,请稍后再试!");
                return;
            }
            name = StringUtils.trimToEmpty(name);
            String time = DateFormatUtils.format(System.currentTimeMillis(), "-MMdd-HHmmss-SSS");
            
            // 空值处理、项目不存在或多个重名项目处理
            List<String> names = gitService.getSubNames(name);
            if (StringUtils.isBlank(name) || names.isEmpty() || names.size() > 1)
            {
                response.setHeader("Content-Disposition", "attachment;filename=error" + time + ".zip");
                try (InputStream is = resource.getInputStream(); OutputStream os = response.getOutputStream())
                {
                    IOUtils.copy(is, os);
                    os.flush();
                }
                return;
            }
            
            // 拉取后打包
            gitService.pull();
            response.setHeader("Content-Disposition", "attachment;filename=" + names.get(0) + time + ".zip");
            try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream()))
            {
                FileUtils.listFilesAndDirs(new File("project/" + names.get(0)), TrueFileFilter.TRUE, DirectoryFileFilter.DIRECTORY)// 递归遍历文件目录
                    .stream()
                    .filter(File::isFile)
                    .collect(Collectors.toList())
                    .forEach(file -> addToZip(zipOutputStream, file));
            }
        }
        finally
        {
            log.info("---- 计数器释放：{}", count.decrementAndGet());
        }
    }
    
    private void addToZip(ZipOutputStream zipOutputStream, File file)
    {
        try (InputStream inputStream = Files.newInputStream(file.toPath()))
        {
            zipOutputStream.putNextEntry(new ZipEntry(StringUtils.substringAfter(file.getCanonicalPath(), "project/")));
            StreamUtils.copy(inputStream, zipOutputStream);
            zipOutputStream.flush();
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
